import * as QiNiu from 'qiniu-js'

 export interface IUploadCallbackParams {
  uploadInfo: {
    /** 上传唯一标识 */
    id: string | number
    /** 上传地址 */
    url: string
  }
  total: {
    /** 已上传大小 单位字节 */
    loaded: number
    /** 上传的大小 单位字节 */
    total: number
    /** 上传进度 */
    percent: number
  }
}

export interface IUploadFileParams{
  /** 文件数据 */
  file: File
  /** 上传token */
  token: string
  /** 文件名，可为空 */
  key?: string
  /** 上传进度回调 */
  nextCallback?: (data: IUploadCallbackParams) => void
  /** 上传完成回调 */
  completeCallback?: (data: any) => void
  /** 上传错误回调 */
  errorCallback?: (data: any) => void
}

export interface IUploadFileAsyncParams{
  /** 文件数据 */
  file: File
  /** 上传token */
  token: string
  /** 文件名，可为空 */
  key?: string
  /** 上传进度回调 */
  nextCallback?: (data: IUploadCallbackParams) => void
}

/**
 * 上传文件
 * @params obj
 */
const  uploadFile = (obj: IUploadFileParams): any => {
  const { file, key, token, nextCallback, completeCallback, errorCallback } = obj

  const observable = QiNiu.upload(file, key || null, token)

  const subscription = observable.subscribe({
    next:(res: any) => nextCallback && nextCallback(res),
    error: (err) => errorCallback && errorCallback(err),
    complete:(res) => completeCallback && completeCallback(res)
  })

  return subscription
}

/**
 * 上传文件
 * @param obj
 */
const uploadFileAsync  = (obj: IUploadFileAsyncParams): Promise<any>  =>{
  return new Promise((resolve, reject) => {
    const { file, key, token, nextCallback } = obj

    const observable = QiNiu.upload(file, key || null, token)

    observable.subscribe({
      next: (res: any) => nextCallback && nextCallback(res),
      error(err): void {
        reject(err)
      },
      complete(res): void {
        resolve(res)
      }
    })
  })
}

export default {
  uploadFile, uploadFileAsync
}

